import { login } from './login'

let baseURL = version();
function version(){
  let version = __wxConfig.envVersion;
  switch (version){
    case 'develop':
      return getApp().globalData.api_url;
      break;
    default:
      return getApp().globalData.api_url;
  }
}

interface header {
  'content-type': string,
  Authorization?: string
}

interface params {
  data?: Object,
  url?: string,
  method?: "GET" | "OPTIONS" | "HEAD" | "POST" | "PUT" | "DELETE" | "TRACE" | "CONNECT" | undefined,
}

export interface IResult<T> {
  code: number,
  msg: string,
  rows?: T,
  data?: Object,
  total?: number
}

interface IResponse<T> {
  data: IResult<T>,
  errMsg?: string
}

export default <T>(params: params) => {
  let data = params.data || {};
  let header: header = {
    'content-type': 'application/json'
  }
  const token = wx.getStorageSync('token')
  if(token){
    header['Authorization'] = `Bearer ${token}`
  }
  return new Promise<IResult<T>>((resolve, reject) => {
    wx.request({
      url: baseURL + params.url,
      method: params.method || "GET",
      data,
      header,
      success: (res: IResponse<T>) => {
        let result = res.data
        if (result.code === 200) {
          resolve(result);
        } else if(result.code === 401){
          getApp().globalData.token = ''
          wx.setStorageSync('token', '')
          wx.showToast({
            title: '需要重新登录',
            icon: 'error'
          });
          login()
          reject(data);
        } else if( typeof(result.code) === 'undefined' ) {
          resolve(result);
        } else {
          wx.showToast({
            title: data.msg,
            icon: "error"
          })
          reject(result);
        }
      },
      fail: err => {
        wx.showToast({
          title: data.msg,
          icon: "error"
        })
        reject(err)
      }
    })
  })
}
